package org.mq.mymq.broker.core;

import org.mq.mymq.broker.cache.CommonCache;
import org.mq.mymq.common.constants.BrokerConstants;
import org.mq.mymq.common.dto.MessageDTO;

import java.io.IOException;

/**
 * @ClassName MessageAppendHandler
 * @Description 处理消息添加和读取
 * @Author jiarong_ye
 * @Date 2025/6/15 15:43
 * @Version 1.0
 */
public class CommitLogAppendHandler {

    public CommitLogAppendHandler() {
    }

    public void prepareMMapLoading(String topicName) throws IOException {
        CommitLogMMapFileModel commitLogMMapFileModel = new CommitLogMMapFileModel();
        commitLogMMapFileModel.loadFileInMMap(topicName, 0, BrokerConstants.COMMITLOG_DEFAULT_SIZE);
        CommonCache.getCommitLogMMapFileModelManager().put(topicName, commitLogMMapFileModel);
    }
    public void appendMsg(MessageDTO messageDTO) throws IOException {
        String topic = messageDTO.getTopic();
        byte[] content = messageDTO.getBody();
        CommitLogMMapFileModel commitLogMMapFileModel = CommonCache.getCommitLogMMapFileModelManager().get(messageDTO.getTopic());
        if (commitLogMMapFileModel == null) {
            throw new RuntimeException("No such topic: " + topic);
        }
        commitLogMMapFileModel.writeContent(messageDTO, true);
    }
}
